package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.EmployeeService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        //这里加密优化
        String password = DigestUtils.md5DigestAsHex((employeeLoginDTO.getPassword() + PasswordConstant.ENCRYPT_PASSWORD).getBytes());
        System.out.println(password);//
//        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //期需要进行md5加密，然后再进行比对
        //md5+特殊字符 改造
        //password = DigestUtils.md5DigestAsHex((password+ PasswordConstant.ENCRYPT_PASSWORD).getBytes());
        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }
    /** 添加员工
    @Override
    */
    public void save(EmployeeDTO dto) {
        //1.将dto转成实体类 copy属性
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto,employee);
        //2.设置特殊属性
        //设置默认密码
        employee.setPassword(DigestUtils.md5DigestAsHex((PasswordConstant.DEFAULT_PASSWORD+PasswordConstant.ENCRYPT_PASSWORD).getBytes()));
        //设置时间
        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());
        //3.封装完成 调用持久层
        employeeMapper.save(employee);
    }

    /**
     * 分页查询
     * @param dto
     */
    public Result<PageResult> page(EmployeePageQueryDTO dto) {
         PageHelper pageHelper = new PageHelper();
         pageHelper.startPage(dto.getPage(),dto.getPageSize());
         //这里是规定好的pagehelper返回的对象
         Page<Employee> result = employeeMapper.QueryPage(dto);
        // Result<Page<Employee>>
        // Result<PageResult>
        PageResult result1 = new PageResult();
        result1.setRecords(result.getResult());
        result1.setTotal(result.getTotal());
        //  没搞懂
         return Result.success(result1);
    }

    /**
     * 账号状态的启用与禁用
     * @param status
     * @param id
     */
    @Override
    public void startOrstop(Integer status, Long id) {
        //这里因为涉及到更新的操作 参数作为 实体类的属性
        // 为了简化后续开发 这里直接定义更新的参数是实体类
        //再用动态sql的方法 判断是否更新
        //使用bulder构建
        Employee emp = Employee.builder()
                .status(status)
                .id(id).build();
        //todo 这里可以扩展判断规则
        employeeMapper.updateData(emp);
    }

    /**
     * id查询员工接口
     * @param id
     */
    @Override
    public Employee selectById(Long id) {
        Employee employee = employeeMapper.selectById(id);
        employee.setPassword("******");
        return employee;
    }

    /**
     * 编辑员工
     * @param dto
     */
    @Override
    public void update(EmployeeDTO dto) {
        //这里做对象转换 dto转entity
        Employee employee = new Employee();
        BeanUtils.copyProperties(dto,employee);
        //设置特殊属性
//        employee.setUpdateTime(LocalDateTime.now());
//        employee.setUpdateUser(BaseContext.getCurrentId());
        System.out.println(employee);
        employeeMapper.updateData(employee);
    }

}
